<script setup lang="ts">
import { useTheme } from "@/composables/useTheme";
import { onLoad, onReady, onShow } from "@dcloudio/uni-app";
import { hidePageNavInWechatBrowser } from "@/composables/useHiddenNavbar";
import { JumpPath, Tips } from "@/utils/index";
import { computed, reactive, toRefs, watch } from "vue";
import footerBtn from "@/components/footerBtn/index.vue";
import { getAdvancedComputing, getGoldMarket } from "@/api/quotation";
import AdvancedHandwritingInput from "@/components/AdvancedHandwritingInput.vue";
import hideWechatMenu from "@/composables/hideWechatMenu";
import { Debounce, debounceImmediate } from "@/utils/validate";
onShow(() => {
  hideWechatMenu();
});
const { colorStyle } = useTheme();
onReady(() => {
  hidePageNavInWechatBrowser();
});
let editorCtx = ref(null);
let type = ref("sale");
let premiumValOptions = ref("");
onLoad((option) => {
  getList();
  if (option.inputValue) {
    nextTick(() => {
      inputValue.value = decodeURIComponent(option.inputValue);
      console.log(inputValue.value, "输入框默认值");
    });
  } else {
    nextTick(() => {
      inputValue.value = "(【au】+ 加减价 ) * (100/100)";
    });
  }
  // type:1销售；2回购
  if (option.type == 1) {
    type.value = "sale";
  } else {
    type.value = "buyback";
  }
  if (option.premiumVal) {
    premiumValOptions.value = option.premiumVal;
    premiumVal.value = option.premiumVal;
  }
});

let list = ref([]);
function getList() {
  getGoldMarket().then((res) => {
    let listData = res.data.filter((item) => item.title != "国际行情");
    if (!listData.length) return;
    listData.forEach((item) => {
      let list = [];
      for (const key in item.list) {
        list.push({
          id: key,
          name: item.list[key],
        });
      }
      item.list = list;
    });
    console.log(listData, "数据");

    list.value = listData;
  });
}
// 创建响应式数据
const show = ref(false);
let isReplace = ref(false);
function insertNewBtn() {
  isReplace.value = false;
  open();
}
// 定义方法
function open() {
  // 打开逻辑，比如设置 show 为 true
  show.value = true;
}

function close() {
  // 关闭逻辑，设置 show 为 false
  show.value = false;
  // console.log('close');
}
// 使用 ref 替代 computed
let hasTieShui = ref(false);

let premiumVal = ref(0);
function submitHandler() {
  if (!formula.value) return Tips({ title: "请填写公式" });
  const params = {
    is_type: type.value, //sale 销售价 buyback 回购价
    premium_val: premiumVal.value, //加减价值
    formula: formula.value, //公式算法 这个保留到数据库
  };
  getAdvancedComputing(params).then((res) => {
    let data = {
      formula: formula.value,
      premiumVal: premiumVal.value,
    };
    if (type.value == "sale") {
      uni.$emit("saleJson", data);
    } else {
      uni.$emit("buybackJson", data);
    }
    uni.navigateBack();
  });
}

let countNum = ref(0);

function chooseHandler(item: any) {
  if (isReplace.value) {
    setNewMarketBtn(item.id);
  } else {
    console.log("新增");
    insertButton(item.id);
  }

  close();
}
// 运算
function calculationHandler() {
  if (!inputValue.value) return Tips({ title: "请填写内容" });
  const params = {
    is_type: type.value, //sale 销售价 buyback 回购价
    premium_val: premiumVal.value, //加减价值
    formula: formula.value, //公式算法 这个保留到数据库
  };
  getAdvancedComputing(params).then((res) => {
    countNum.value = res.data.price;
  });
}
const formula = computed(() => processContent(inputValue.value));

function modelValue(e) {
  checkForTieShui();
}
const inputValue = ref("");

// 处理HTML内容的函数
const processContent = (htmlContent: string) => {
  // 使用正则表达式匹配 styled-button span 标签
  let result = htmlContent.replace(
    /<span[^>]*class="[^"]*styled-button[^"]*"[^>]*data-content="[^"]*"[^>]*>([^<]*)<\/span>/g,
    (match, content) => {
      // 去除首尾空白字符
      const textContent = content.trim();

      if (textContent === "加减价") {
        // 如果是"加减价"，只返回文本内容，不包含标签
        return textContent;
      } else {
        // 如果不是"加减价"，用【】包裹内容
        return `【${textContent}】`;
      }
    }
  );

  // 移除所有 span 标签，保留其中的内容
  result = result.replace(/<span[^>]*>([^<]*)<\/span>/g, "$1");

  // 移除其他 HTML 标签
  result = result.replace(/<[^>]*>/g, "");

  // 处理常见 HTML 实体
  result = result
    .replace(/&nbsp;/g, " ")
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'");

  return result.trim();
};
// 监听输入框值的变化
watch(
  inputValue,
  (newVal) => {
    hasTieShui.value = processContent(newVal).includes("加减价");

    // 在这里处理您的业务逻辑
    // 例如：实时验证、字符计数、自动保存等
  },
  { immediate: true }
);
// 创建检查加减价内容的方法
function checkForTieShui(e) {
  // 更新 hasTieShui 的值
  hasTieShui.value = inputRef.value.getContent().includes("加减价");
}

const inputRef = ref<InstanceType<typeof AdvancedHandwritingInput> | null>(
  null
);
// 插入带样式的按钮
const insertButton = (type) => {
  if (inputRef.value) {
    if (type === "加减价") {
      const timestamp = Date.now();
      inputRef.value.insertButtonAtCursor(`button_${timestamp}`, `加减价`);
    } else {
      const timestamp = Date.now();
      inputRef.value.insertButtonAtCursor(`button_${timestamp}`, type);
    }
  }
  nextTick(() => {
    if (inputRef.value) {
      setTimeout(() => {
        inputRef.value.focus();
      }, 1000);
    }
  });
};
function setNewMarketBtn(displayText: string) {
  // 直接使用传递过来的按钮元素进行替换
  if (inputRef.value) {
    // 生成新按钮内容
    const newTimestamp = Date.now();
    const newContent = `new_button_${newTimestamp}`;
    const newDisplayText = displayText;

    // 替换按钮
    inputRef.value.replaceButton(
      buttonElementRef.value,
      newContent,
      newDisplayText
    );
    inputRef.value.focus();
  }
}
let buttonElementRef = ref(null);
// const onButtonClick = (displayText: string, buttonElement: HTMLElement) => {
//   isReplace.value = true;
//   if (displayText == "加减价") return;
//   buttonElementRef.value = buttonElement;
//   open();
//   // 直接使用传递过来的按钮元素进行替换
// };
// 处理按钮点击事件 - 替换为新按钮
const onButtonClick = (
  content: string,
  displayText: string,
  buttonElement: HTMLElement
) => {
  if (displayText == "加减价") return;
  isReplace.value = true;
  buttonElementRef.value = buttonElement;
  open();
};
// 解决步进器全删后自动变为最低值start-------------
const premiumValChange = Debounce(premiumValDebounce, 1500);
function premiumValDebounce(e) {
  console.log(1111111);

  if (e.value == -100) return;
  premiumVal.value = e.value;
}
function premiumValBlur(e) {
  console.log(e.value === "", "-----");

  if (e.value === "") {
    premiumVal.value = premiumValOptions.value;
  }
}
// 解决步进器全删后自动变为最低值end-------------
</script>
<template>
  <view class="wrap pad30" :style="colorStyle">
    <view class="btn_box flex_se">
      <view
        class="btn_item pad1030"
        :class="{ gray_btn: hasTieShui }"
        @click="insertButton('加减价')"
      >
        插入加减价
      </view>
      <view class="btn_item pad1030" @click="insertNewBtn"> 插入行情 </view>
    </view>
    <view class="editor_box mgt16">
      <AdvancedHandwritingInput
        v-model="inputValue"
        placeholder="请输入内容"
        ref="inputRef"
        @button-click="onButtonClick"
        @insert-button-request="onInsertButtonRequest"
        @modelValue="modelValue"
      />
    </view>

    <view class="set_item mgt16 pad2030 flex_sb">
      <text class="label_name">加减价</text>
      <u-number-box
        v-model="premiumVal"
        :min="-100"
        :step="0.01"
        inputWidth="60"
        @change="premiumValChange"
        @blur="premiumValBlur"
        :asyncChange="true"
      ></u-number-box>
    </view>
    <view class="set_item mgt16 pad2030 flex_sb">
      <text class="label_name">运算值：{{ countNum }}</text>
      <view class="right_btn pad1030" @click="calculationHandler"> 运算 </view>
    </view>
    <view class="tip_box">
      <view> 【添加公式】 </view>
      <view>公式支持 +、-、*、/、() 的四则运算;</view>
      <view>公式可插入多个行情源标签 和 1个升加减价标签;</view>
      <view>点击行情源标签可修改行情;</view>
    </view>
    <footerBtn title="确认策略" @submitHandler="submitHandler" />

    <up-popup
      :show="show"
      :safeAreaInsetBottom="false"
      @close="close"
      @open="open"
      :round="20"
    >
      <view class="pop_box">
        <scroll-view scroll-y style="height: 100%">
          <view class="data_item" v-for="(item, index) in list" :key="index">
            <view class="title">{{ item.title }}</view>
            <view class="info">
              <view
                class="switch_item pad2030 flex_sb"
                v-for="(_item, _index) in item.list"
                :key="_index"
                @click="chooseHandler(_item)"
              >
                <text>{{ _item.id + "-" + _item.name }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </up-popup>
  </view>
</template>

<style scoped lang="scss">
.wrap {
  .pop_box {
    height: 600rpx;
    overflow: hidden;
    border-radius: 20rpx 20rpx 0 0;
    .data_item {
      .title {
        color: rgba(125, 136, 140, 1);
        font-size: 28rpx;
        padding: 16rpx 30rpx;
      }
      .info {
        .switch_item {
          font-size: 30rpx;
          background: #fff;
          color: rgba(39, 38, 54, 1);
          &:not(:last-child) {
            margin-bottom: 2rpx;
          }
        }
      }
    }
  }
  .set_item {
    background: #fff;
    color: rgba(39, 38, 54, 1);
    font-size: 30rpx;
    .label_name {
      margin-right: 30rpx;
      flex-shrink: 0;
    }
    .right_btn {
      border: 2rpx solid rgba(0, 0, 0, 1);
      border-radius: 30rpx;
      background: rgba(255, 255, 255, 1);
      font-size: 26rpx;
      color: #000;
    }
  }
  .btn_box {
    margin: 20rpx 0;

    .btn_item {
      font-size: 26rpx;
      margin-left: 20rpx;
      color: #fff;
      background: #272636;
      border-radius: 99rpx;
    }
    .gray_btn {
      background: #999;
      pointer-events: none;
    }
  }
  .editor_box {
    font-size: 30rpx;
    color: rgba(28, 28, 29, 1);
    width: 100%;
    min-height: 241rpx;
    border-radius: 8rpx;
    background: rgba(255, 255, 255, 1);
    .editor_container {
      width: 100%;
      height: 100%;
    }
  }
  .tip_box {
    color: rgba(125, 136, 140, 1);
    font-size: 28rpx;
    line-height: 43rpx;
    text-align: left;
    margin-bottom: 20rpx;
  }
}
</style>
